#include<iostream>
#include"../Comm/httplib.h"
#include"Control.hpp"

static OnlineOJ::ns_Control::Control *ctrl_ptr = nullptr;

void Recovery(int signo)
{
    ctrl_ptr->RecoveryMachines();
}


int main()
{
    signal(10,Recovery);

    //用户请求服务路由功能
    
    httplib::Server server;
    OnlineOJ::ns_Control::Control ctrl;
    ctrl_ptr=&ctrl;

    //获取题目列表
    server.Get("/all_questions",[&ctrl](const httplib::Request& req,httplib::Response& resp){
        //获取题目列表的HTML网页
        std::string html;
        bool ret=ctrl.AllQuestionsHTML(html);
        if(ret)
        {
            resp.set_content(html,"text/html;charset=utf-8");
        }
    });

    //根据题目编号获取题目内容
    //(\d+)：正则匹配，'\d'表示匹配数字，'+'表示匹配一个或多个
    //R"(...)"：保持原始字符串内容原样，不做特殊处理
    server.Get(R"(/questions/(\d+))",[&ctrl](const httplib::Request& req,httplib::Response& resp){
        //获取题目编号
        std::string num=req.matches[1];
        //获取对应题目的HTML页面
        std::string html;
        bool ret=ctrl.QuestionHTML(num,html);
        if(ret)
        {
            resp.set_content(html,"text/html;charset=utf-8");
        }
    });

    //判题(1.题目的测试用例，2.编译运行用户提交的代码)
    server.Post(R"(/judge/(\d+))",[&ctrl](const httplib::Request& req,httplib::Response& resp){
        //获取题目编号
        std::string num=req.matches[1];
        // resp.set_content("判定题目："+num,"text/plain;charset=utf-8");
        std::string res_json;
        ctrl.Judge(num,req.body,res_json);
        resp.set_content(res_json,"application/json;charset=utf-8");
    });
    //设置根目录
    server.set_base_dir("./wwwroot");
    //启动监听
    server.listen("0.0.0.0",8888);

    return 0;
}